<template>
  <el-steps
    align-center
    finish-status="success"
    style="margin-bottom: var(--space-large)"
    :active="active"
  >
    <el-step title="基本信息"></el-step>
    <el-step title="商品详情"></el-step>
    <el-step title="其它信息"></el-step>
  </el-steps>
  <el-form
    v-show="active === 0"
    v-loading="isGettingProductInfo"
    label-width="140px"
    ref="productFormIns"
    :model="productForm"
    :rules="productFormRules"
    @submit.prevent="handleSubmit"
  >
    <el-form-item label="Name" prop="store_name">
      <el-input v-model="productForm.store_name"></el-input>
    </el-form-item>
    <el-form-item label="Category" prop="cate_id">
      <el-cascader
        v-model="productForm.cate_id"
        :options="categoryList"
        :props="{
          label: 'cate_name',
          value: 'id',
          emitPath: false,
          multiple: true,
        }"
      ></el-cascader>
    </el-form-item>
    <el-form-item label="Keyword">
      <el-input v-model="productForm.keyword"></el-input>
    </el-form-item>
    <el-form-item label="Unit">
      <el-input v-model="productForm.unit_name"></el-input>
    </el-form-item>
    <el-form-item label="Summary" prop="store_info">
      <el-input v-model="productForm.store_info"></el-input>
    </el-form-item>
    <el-form-item label="主图" prop="image">
      <ImageManager v-model="productForm.image" />
    </el-form-item>
    <el-form-item label="轮播图" prop="slider_image">
      <ImageManager v-model="productForm.slider_image" :max="10" />
    </el-form-item>
    <el-form-item label="推荐图">
      <ImageManager v-model="productForm.recommend_image" />
    </el-form-item>
    <el-form-item label="规格类型">
      <el-radio v-model="productForm.spec_type" :label="0">单规格</el-radio>
      <el-radio v-model="productForm.spec_type" :label="1">多规格</el-radio>
      <!-- 单规格 -->
      <div v-if="productForm.spec_type === 0">
        <el-table border :data="singleProductAttr">
          <el-table-column label="图片" key="image" width="80">
            <template #default="{ row }">
              <ImageManager v-model="row.pic" width="50px" height="50px" />
            </template>
          </el-table-column>
          <el-table-column
            v-for="item in productAttrParams"
            :label="item.label"
            :prop="item.prop"
            :key="item.prop"
          >
            <template #default="{ row }">
              <el-input v-model="row[item.prop]"></el-input>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <!-- 多规格 -->
      <div v-if="productForm.spec_type === 1">
        <div style="display: flex; margin-bottom: var(--space-small)">
          <el-select v-model="multiAttrTemplate" placeholder="选择规格模板">
            <el-option
              v-for="item in productAttrList"
              :key="item.id"
              :value="item.id"
              :label="item.rule_name"
            ></el-option>
          </el-select>
          <el-button
            @click="handleSelectAttrTemplate"
            style="margin: 0 var(--space-small)"
            type="primary"
          >确定</el-button>
          <router-link to="/product/attr">
            <el-button>添加新规格模板</el-button>
          </router-link>
        </div>

        <Dragger v-model="multiAttrList" handle=".handler">
          <div v-for="item in multiAttrList" class="multi-attr-list" :key="item.label">
            <el-icon
              :size="16"
              style="margin-right: var(--space-small); cursor: move"
              class="handler"
            >
              <Sort />
            </el-icon>
            <el-input size="mini" style="width: 100px" v-model="item.label">{{ item.label }}</el-input>
            <span style="margin: 0 var(--space-tiny)">：</span>
            <Dragger v-model="item.value">
              <el-tag
                closable
                size="medium"
                style="margin: 0 var(--space-small) 0 0"
                v-for="attr in item.value"
                :key="attr"
                @close="handleRemoveAttrValue(item, attr)"
              >{{ attr }}</el-tag>
            </Dragger>
            <el-input
              size="mini"
              style="width: 160px"
              v-model="item.inputValue"
              @keydown.enter.prevent="handleInsertAttrValue(item)"
            >
              <template #append>
                <el-button @click="handleInsertAttrValue(item)">+</el-button>
              </template>
            </el-input>
            <el-button
              size="mini"
              type="danger"
              style="margin-left: auto"
              @click="handleRemoveAttr(item)"
            >删除</el-button>
          </div>
        </Dragger>

        <template v-if="multiAttrList.length">
          <div class="multi-attr-list">
            <el-input
              size="mini"
              v-model="newAttrName"
              style="margin-right: var(--space-small)"
              placeholder="输入规格名称"
            ></el-input>
            <el-button
              size="mini"
              type="primary"
              style="margin-left: auto"
              @click="handleInsertNewAttr"
            >添加</el-button>
          </div>
          <div>
            <el-button
              type="primary"
              style="display: block; width: 100%"
              :loading="isGeneratingSKU"
              :disabled="multiAttrList.length < 1"
              @click="handleGenSKU"
            >立即生成</el-button>
          </div>
          <template v-if="productForm.attrs.length">
            <h4>批量设置</h4>
            <el-table border :data="multiAttrBatchSKUData">
              <el-table-column label="图片" width="80">
                <template #default="{ row }">
                  <ImageManager v-model="row.pic" width="50px" height="50px" />
                </template>
              </el-table-column>
              <el-table-column
                v-for="item in productAttrParams"
                :label="item.label"
                :prop="item.prop"
                :key="item.prop"
              >
                <template #default="{ row }">
                  <el-input v-model="row[item.prop]"></el-input>
                </template>
              </el-table-column>
              <el-table-column label="操作" fixed="right" align="right">
                <template #default="{ row }">
                  <el-button
                    size="mini"
                    type="primary"
                    @click="handleSetMultiAttrSKUBatch(row)"
                  >批量设置</el-button>

                  <el-button size="mini" @click="handleClearMultiAttrBatchSKUData">清空</el-button>
                </template>
              </el-table-column>
            </el-table>
            <h4>商品属性</h4>
            <el-table border :data="productForm.attrs">
              <el-table-column
                v-for="item in productForm.header"
                :key="item.title"
                :prop="item.key"
                :label="item.title"
              ></el-table-column>
              <el-table-column label="图片" width="80">
                <template #default="{ row }">
                  <ImageManager v-model="row.pic" width="50px" height="50px" />
                </template>
              </el-table-column>
              <el-table-column
                v-for="item in productAttrParams"
                :label="item.label"
                :prop="item.prop"
                :key="item.prop"
              >
                <template #default="{ row }">
                  <el-input v-model="row[item.prop]"></el-input>
                </template>
              </el-table-column>
              <el-table-column label="操作" fixed="right" width="80">
                <template #default="{ $index }">
                  <el-button size="mini" type="danger" @click="handleDeleteMultiAttrSKU($index)">删除</el-button>
                </template>
              </el-table-column>
            </el-table>
          </template>
        </template>
      </div>
      <!-- 多规格 END -->
    </el-form-item>
    <el-form-item>
      <el-button type="primary" native-type="submit">Next Step</el-button>
    </el-form-item>
  </el-form>
  <el-form v-show="active === 1" @submit.prevent="handleSubmit" label-width="140px">
    <el-form-item label="商品详情">
      <div id="product-desc-editor"></div>
    </el-form-item>
    <el-form-item>
      <el-button @click="handlePreviousStep">Previous Step</el-button>
      <el-button type="primary" native-type="submit">Next Step</el-button>
    </el-form-item>
  </el-form>
  <el-form v-show="active === 2" @submit.prevent="handleSubmit" label-width="140px">
    <el-form-item label="虚拟销量">
      <el-input-number v-model="productForm.ficti" :min="0"></el-input-number>
    </el-form-item>
    <el-form-item label="积分">
      <el-input-number v-model="productForm.give_integral"></el-input-number>
    </el-form-item>
    <el-form-item label="排序">
      <el-input-number v-model="productForm.sort"></el-input-number>
    </el-form-item>
    <el-form-item label="是否展示">
      <el-switch v-model="productForm.is_show" :active-value="1" :inactive-value="0"></el-switch>
    </el-form-item>
    <el-form-item label="是否热卖">
      <el-switch v-model="productForm.is_hot" :active-value="1" :inactive-value="0"></el-switch>
    </el-form-item>
    <el-form-item label="是否优惠">
      <el-switch v-model="productForm.is_benefit" :active-value="1" :inactive-value="0"></el-switch>
    </el-form-item>
    <el-form-item label="是否精品">
      <el-switch v-model="productForm.is_best" :active-value="1" :inactive-value="0"></el-switch>
    </el-form-item>
    <el-form-item label="是否新品">
      <el-switch v-model="productForm.is_new" :active-value="1" :inactive-value="0"></el-switch>
    </el-form-item>
    <el-form-item label="是否优品推荐">
      <el-switch v-model="productForm.is_good" :active-value="1" :inactive-value="0"></el-switch>
    </el-form-item>
    <el-form-item label="活动优先级">
      <Dragger v-model="productForm.activity">
        <el-tag v-for="tag in productForm.activity" :key="tag" :type="getTagType(tag)">{{ tag }}</el-tag>
      </Dragger>
    </el-form-item>
    <el-form-item>
      <el-button @click="handlePreviousStep">Previous Step</el-button>
      <el-button type="primary" native-type="submit" :loading="isSubmitting">Submit</el-button>
    </el-form-item>
  </el-form>
  <el-result
    v-if="active === 3"
    icon="success"
    :title="productForm.store_name + (id ? ' 保存成功' : ' 添加成功')"
  >
    <template #extra>
      <el-button type="primary" @click="insertAgain">继续添加</el-button>
    </template>
  </el-result>
</template>
<script setup lang="ts">
import { ref, watch, nextTick, onMounted } from 'vue'
import { useRoute, useRouter } from 'vue-router'

import {
  genProductMultiAttr,
  getProductInfo,
  submitProduct,
} from '@/api/product'

import { Sort } from '@element-plus/icons'
import { ElMessage } from 'element-plus'

import useProductCategory from '@/pages/product/category/index'
import useProductAttr from '@/pages/product/attr/index'

import ImageManager from '@/components/image-manager/index.vue'
import Dragger from '@/components/dragger/index.vue'

import E from 'wangeditor'

// 1. 获取商品 ID（如果有）、商品信息
const id = ref(0)
const route = useRoute()
const isGettingProductInfo = ref(false)
watch(
  () => route.query.id,
  val => {
    if (val !== undefined) {
      isGettingProductInfo.value = true
      id.value = Number(val)
      getProductInfo(id.value)
        .then(res => {
          productForm.value = Object.assign(
            productForm.value,
            res.productInfo,
            { cate_id: res.productInfo.cate_id.map(item => Number(item)) }
          )
          singleProductAttr.value = [res.productInfo.attr]
          //
          multiAttrList.value = res.productInfo.items.map(item => {
            return {
              label: item.value,
              value: item.detail,
              inputValue: '',
            }
          })
          //
          genProductMultiAttr(0, 1, {
            attrs: res.productInfo.items,
          }).then(({ info: { header } }) => {
            productForm.value.header = header.filter(item => 'key' in item)
          })
        })
        .finally(() => {
          isGettingProductInfo.value = false
        })
    }
  },
  { immediate: true }
)

// 2. 获取商品分类
const { categoryList, handleGetCategoryList } = useProductCategory()
handleGetCategoryList()

// 3. 准备商品表单
const productForm = ref<ProductFormType>({
  // 基本信息
  store_name: '',
  cate_id: [],
  keyword: '',
  unit_name: '',
  store_info: '',
  image: '',
  slider_image: [],
  recommend_image: '',
  attrs: [],
  header: [],
  items: [],
  // 详情
  description: '',
  // 其它信息
  give_integral: 0,
  is_show: 0,
  is_hot: 0,
  is_benefit: 0,
  is_best: 0,
  is_new: 0,
  is_postage: 0,
  is_good: 0,
  spec_type: 0,
  ficti: 0,
  sort: 0,
  activity: ['默认', '秒杀', '砍价', '拼团'],
  // 暂时没有用到
  coupon_ids: '',
  label_id: '',
  command_word: '',
  temp_id: '',
  mer_use: '',
  postage: '',
  video_link: '',
})

const productFormRules = ref({
  store_name: [{ required: true, message: '请输入商品名称' }],
  cate_id: [{ required: true, message: '请选择商品分类' }],
  image: [{ required: true, message: '请上传商品主图' }],
  slider_image: [
    { required: true, type: 'array', message: '请上传商品轮播图' },
  ],
})

const active = ref(0)

function getTagType(tag: string) {
  if (tag === '秒杀') {
    return 'success'
  }
  if (tag === '砍价') {
    return 'warning'
  }
  if (tag === '拼团') {
    return 'danger'
  }
  return ''
}

// 4. 处理商品规格

// 商品规格参数
const productAttrParams = ref<{ label: string; prop: string }[]>([
  { label: '售价', prop: 'price' },
  { label: '成本价', prop: 'cost' },
  { label: '原价', prop: 'ot_price' },
  { label: '库存', prop: 'stock' },
  { label: '重量 KG', prop: 'weight' },
  { label: '体积 m³', prop: 'volume' },
  { label: '产品编号', prop: 'bar_code' },
])

// 默认商品规格参数
const defaultAttr = {
  pic: '',
  price: 0,
  vip_price: 0,
  cost: 0,
  ot_price: 0,
  stock: 0,
  bar_code: '',
  weight: 0,
  volume: 0,
  brokerage: 0,
  brokerage_two: 0,
}

// 单规格商品参数
const singleProductAttr = ref([
  {
    ...defaultAttr,
  },
])

// 多规格

const { handleGetProductAttrList, productAttrList } = useProductAttr() // 规格模板列表
const multiAttrTemplate = ref(null) // 当前选中的规格模板
handleGetProductAttrList()

interface ProductAttrLocalType {
  label: string
  value: string[]
  inputValue: string
}

const multiAttrList = ref<ProductAttrLocalType[]>([])

function handleSelectAttrTemplate() {
  const value = productAttrList.value.find(
    item => item.id === multiAttrTemplate.value
  )

  if (value) {
    multiAttrList.value = value.attr_name.split(',').map((item, index) => {
      return {
        label: item,
        value: value.attr_value[index].split(','),
        inputValue: '',
      }
    })
  }
}

const newAttrName = ref('')

function handleInsertNewAttr() {
  if (newAttrName.value === '') {
    return
  }

  if (multiAttrList.value.find(item => item.label === newAttrName.value)) {
    ElMessage.error(`${newAttrName.value} 已存在`)
    return
  }

  multiAttrList.value.push({
    label: newAttrName.value,
    value: [],
    inputValue: '',
  })

  newAttrName.value = ''
}

function handleRemoveAttr(item: ProductAttrLocalType) {
  multiAttrList.value = multiAttrList.value.filter(
    (a: ProductAttrLocalType) => a !== item
  )
}

function handleInsertAttrValue(item: ProductAttrLocalType) {
  if (item.inputValue === '') {
    return
  }

  if (item.value.find(val => val === item.inputValue)) {
    ElMessage.error(`${item.inputValue} 已存在`)
    return
  }

  item.value.push(item.inputValue)
  item.inputValue = ''
}

function handleRemoveAttrValue(item: ProductAttrLocalType, attr: string) {
  item.value = item.value.filter((a: string) => a !== attr)
}

// 清除多规格下的批量设置表格的数据
function handleClearMultiAttrBatchSKUData() {
  multiAttrBatchSKUData.value = [{ ...defaultAttr }]
}

const multiAttrBatchSKUData = ref<AttrTableDataType[]>([{ ...defaultAttr }])
const isGeneratingSKU = ref(false)

// 立即生成
function handleGenSKU() {
  isGeneratingSKU.value = true
  genProductMultiAttr(0, 1, {
    attrs: multiAttrList.value.map(item => ({
      value: item.label,
      detail: item.value,
    })),
  })
    .then(({ info: { header, value } }) => {
      productForm.value.header = header.filter(item => 'key' in item)
      productForm.value.attrs = value
    })
    .finally(() => {
      nextTick(() => {
        isGeneratingSKU.value = false
      })
    })
}

// 删除多规格下的商品
function handleDeleteMultiAttrSKU(index: number) {
  productForm.value.attrs = productForm.value.attrs.filter(
    (item, i) => i !== index
  )
}

// 批量设置多规格下的商品属性
function handleSetMultiAttrSKUBatch(row: AttrTableDataType) {
  productForm.value.attrs.forEach(item => {
    Object.keys(row).forEach(key => {
      item[key] = row[key]
    })
  })
}

// 商品详情
let editor: E

onMounted(() => {
  editor = new E('#product-desc-editor')
  editor.create()
})

// 上一步
function handlePreviousStep() {
  active.value--
}

// 下一步、 提交
const productFormIns = ref(null)
const isSubmitting = ref(false)

function handleSubmit() {
  const form = productFormIns.value as any

  switch (active.value) {
    case 0:
      form.validate((valid: boolean) => {
        valid && active.value++
        // 设置商品详情
        editor.txt.html(productForm.value.description)
      })
      break
    case 1:
      const des = editor.txt.html()
      if (!des) {
        ElMessage.error('请输入商品详情')
        return
      }
      productForm.value.description = des
      active.value++
      break
    case 2:
      isSubmitting.value = true

      // 保存单规格、多规格数据
      if (productForm.value.spec_type === 0) {
        productForm.value.attrs = singleProductAttr.value
      } else if (productForm.value.spec_type === 1) {
        productForm.value.items = multiAttrList.value.map(item => ({
          value: item.label,
          detail: item.value,
        }))
      }

      submitProduct(id.value, productForm.value)
        .then(() => {
          active.value++
        })
        .finally(() => {
          isSubmitting.value = false
        })
      break
  }
}

const router = useRouter()

function insertAgain() {
  router.push('/product/insert').then(() => router.go(0))
}
</script>

<style lang="scss">
</style>
